package sk.tramtatiri.data.dao.jpa;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import sk.tramtatiri.data.dao.interfaces.UserFoodDao;
import sk.tramtatiri.data.dataobjects.UserFood;

public class UserFoodDaoJPAImp extends AbstractDaoJPAImpl<UserFood> implements
		UserFoodDao {

	public UserFoodDaoJPAImp() {
		super(UserFood.class);
	}

	public List<UserFood> findAll() {
		return getJpaTemplate().execute(new JpaCallback<List<UserFood>>() {
			public List<UserFood> doInJpa(EntityManager em)
					throws PersistenceException {
				TypedQuery<UserFood> query = em.createQuery(
						"select uf from UserFood uf", UserFood.class);
				return query.getResultList();
			}
		});
	}

	public int countAll() {
		// TODO Auto-generated method stub
		return 0;
	}

	public UserFood findName(String name) {
		// TODO Auto-generated method stub
		return null;
	}

	@Transactional
	public int sumUserToday(final long user_id) {
		Calendar c = Calendar.getInstance();
		c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
				c.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
		final Date date = new Date(c.getTimeInMillis());
		try {
			return getJpaTemplate().execute(new JpaCallback<Integer>() {
				public Integer doInJpa(EntityManager em)
						throws PersistenceException {
					TypedQuery<Long> query0 = em
							.createQuery(
									"select sum(uf.totalCalories) from UserFood uf where uf.user_id = :userId and uf.date = :today",
									Long.class);
					query0.setParameter("today", date);
					query0.setParameter("userId", user_id);
					return (query0.getSingleResult()).intValue();
				}
			});
		} catch (Exception e) {
			return 0;
		}
	}

	@Transactional
	public List<Object[]> findAllByDate(final long user_id, final Date date) {
		return getJpaTemplate().execute(new JpaCallback<List<Object[]>>() {
			public List<Object[]> doInJpa(EntityManager em)
					throws PersistenceException {
				
					Query query0 = em
							.createQuery("select f,uf from UserFood uf, Food f where f.id = uf.food_id and uf.user_id = :userId and uf.date = :date order by f.name asc");
					query0.setParameter("date", date);
				
				query0.setParameter("userId", user_id);
				return query0.getResultList();
			}
		});
	}

	@Transactional
	public void delete(UserFood o) {
		UserFood uf = getJpaTemplate().find(UserFood.class, o.getId());
		getJpaTemplate().remove(uf);
	}

}
